﻿using Owin;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using Sustainalytics.Utils;
using Sustainalytics.Portfolios.Service.Infrastructure;
using Sustainalytics.Portfolios.Service.Utility;
using System;
using System.Timers;
using System.IO;

namespace Sustainalytics.Portfolios.Service
{
    public class Startup
    {
        private static DateTime _creationDay { get; set; }
        public static void Configuration(IAppBuilder builder)
        {
            builder.UseAuthenticationServer();

            var config = new HttpConfiguration();
            builder.Use<OwinExceptionMiddleware>();

            var container = PortfolioCompositionRoot.RegisterAsync(config);

            config.Services.Replace(typeof(IHttpControllerActivator), new SimpleInjectorControllerActivator(container));
            config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));

            config.Routes.MapHttpRoute(
                name: "ApiById",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { id = @"^[0-9]+$" });
            config.Routes.MapHttpRoute(
                name: "ApiByType",
                routeTemplate: "api/{controller}/{type}/{id}",
                defaults: new { controller = "portfolios", id = RouteParameter.Optional },
                constraints: new { id = @"^[0-9]+$" });

            WebApiConfig.Register(config);
            config.Filters.Add(new CustomExceptionFilter());
            config.Filters.Add(new ClaimFilter(ClaimsCheckerSingleton.Instance));
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            builder.UseWebApi(config);

            StartTimer();
            config.EnsureInitialized();
        }

        public static void StartTimer()
        {
            Timer aTimer = new Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 3600 * 1000;
            aTimer.Enabled = true;
        }

        public static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\Log\";

            string filename = filepath + "log.txt";

            if (File.Exists(filename))
            {
                _creationDay = File.GetCreationTime(filename);
                if (_creationDay.AddDays(20).Date == DateTime.Now.Date)
                {
                    File.Delete(filename);
                }
            }
        }

        protected Startup()
        {

        }
    }
}
